import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyrefresh/ball_pulse_footer.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_shop/components/activetyPanel.dart';
import 'package:flutter_shop/components/adBanners.dart';
import 'package:flutter_shop/components/floorLayer.dart';
import 'package:flutter_shop/components/leaderPhone.dart';
import 'package:flutter_shop/components/recommend.dart';
import 'package:flutter_shop/components/swiper.dart';
import 'package:flutter_shop/components/topNavigator.dart';
import 'package:flutter_shop/helpers/Api.dart';

// NOTE: 图片会导致溢出

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  String homePageContent = "正在获取数据";
  // TextEditingController _typeController = TextEditingController();

  int page = 1;
  List<Map> hotGoodsList = [];

  Widget hotTitle = Container(
    margin: EdgeInsets.only(top: 10.0),
    padding: EdgeInsets.all(5.0),
    alignment: Alignment.center,
    decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(width: 0.5, color: Colors.black12))),
    child: Text("火爆专区"),
  );

  @override
  void initState() {
    this._getHotGoods();
    super.initState();
  }

  Future _getHotGoods() async {
    var res = await Api.getHomePageBelowConten(this.page);
    List<Map> newGoodsList = (res.data as List).cast();
    this.setState(() {
      this.hotGoodsList.addAll(newGoodsList);
      this.page++;
    });
  }

  Widget _wrapList() {
    if (this.hotGoodsList.length == 0) {
      return Text("");
    }
    List<Widget> listWidget = this.hotGoodsList.map((item) {
      return InkWell(
        onTap: () {
          print("点击火爆商品");
        },
        child: Container(
          width: ScreenUtil().setWidth(372.0),
          color: Colors.white,
          padding: EdgeInsets.all(5.0),
          margin: EdgeInsets.only(bottom: 3.0),
          child: Column(
            children: <Widget>[
              Image.network(
                item["image"],
                width: ScreenUtil().setWidth(375.0),
              ),
              Text(
                item["name"],
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
              ),
              Row(
                children: <Widget>[
                  Text("￥${item['mallPrice']}"),
                  Text("￥${item['price']}",
                      style: TextStyle(
                          color: Colors.black26,
                          decoration: TextDecoration.lineThrough)),
                ],
              )
            ],
          ),
        ),
      );
    }).toList();
    return Wrap(
      spacing: 2,
      children: listWidget,
    );
  }

  Future _getHomePageData() async {
    try {
      var result = await Api.getHomePageContent();
      if (result.code != "0") {
        return "服务器错误";
      } else {
        return result.data;
      }
    } catch (e) {
      print(e);
      return null;
    }
  }

  Widget _renderSwiperDiy(AsyncSnapshot snapshot) {
    List<Map> swiperDataList = (snapshot.data["slides"] as List).cast();
    return SwiperDiy(swiperDataList: swiperDataList); //页面顶部轮播组件
  }

  Widget _renderTopMenuPanel(AsyncSnapshot snapshot) {
    List<Map> menuList = (snapshot.data["category"] as List).cast();
    if (menuList.length > 10) {
      menuList.removeRange(10, menuList.length);
    }
    return TopNavigator(navigatorList: menuList);
  }

  Widget _renderAdBannerPanel(AsyncSnapshot snapshot) {
    String advertesPicture = snapshot.data['advertesPicture']['PICTUREADDRESS'];
    return AdBanners(advertesPicture: advertesPicture);
  }

  Widget _renderCallPhonePanel(AsyncSnapshot snapshot) {
    String leaderImage = snapshot.data['shopInfo']['leaderImage']; //店长图片
    String leaderPhone = snapshot.data['shopInfo']['leaderPhone']; //店长电话
    return LeaderPhone(leaderImage: leaderImage, leaderPhone: leaderPhone);
  }

  Widget _renderRecommendPanel(AsyncSnapshot snapshot) {
    List<Map> recommendList =
        (snapshot.data['recommend'] as List).cast(); // 商品推荐
    return Recommend(recommendList: recommendList);
  }

  Widget _renderActivetyPanel(AsyncSnapshot snapshot) {
    List<String> imgList = [
      snapshot.data["saoma"]["PICTUREADDRESS"],
      snapshot.data["integralMallPic"]["PICTUREADDRESS"],
      snapshot.data["newUser"]["PICTUREADDRESS"],
    ];
    return ActivetyPanel(imgList: imgList);
  }

  Widget _renderFloorLayer(AsyncSnapshot snapshot, String idx) {
    String k1 = "floor$idx";
    String k2 = "floor${idx}Pic";
    String titleSrc = snapshot.data[k2]["PICTUREADDRESS"];
    List floorGoodsList = (snapshot.data[k1] as List).cast();
    return FloorLayer(titleSrc: titleSrc, floorGoodsList: floorGoodsList);
  }

  Future _onRefreshLoad() async {
    return await this._getHotGoods();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return Scaffold(
      appBar: AppBar(title: Text("百姓生活++"), centerTitle: true),
      backgroundColor: Color(0xfff7f7f7),
      body: FutureBuilder(
        future: this._getHomePageData(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            // floor 1
            // 纵向滚动
            return EasyRefresh(
              onLoad: this._onRefreshLoad,
              footer: BallPulseFooter(),
              child: ListView(
                scrollDirection: Axis.vertical,
                children: <Widget>[
                  this._renderSwiperDiy(snapshot),
                  this._renderTopMenuPanel(snapshot),
                  this._renderAdBannerPanel(snapshot),
                  this._renderCallPhonePanel(snapshot),
                  this._renderActivetyPanel(snapshot),
                  this._renderRecommendPanel(snapshot),
                  this._renderFloorLayer(snapshot, "1"),
                  this._renderFloorLayer(snapshot, "2"),
                  this._renderFloorLayer(snapshot, "3"),
                  hotTitle,
                  this._wrapList()
                ],
              ),
            );
          } else {
            return Center(
                child: Container(
                    height: ScreenUtil().setHeight(80.0),
                    child: Image.asset("assets/imgs/home/loading.gif")));
          }
        },
      ),
    );
  }
}

// FutureBuilder 是一个内置组件,用来等待异步请求的; 异步渲染的问题
/*
  ScreenUtil.pixelRatio : 设备的像素密度
  ScreenUtil.screenWidth : 设备的宽度
  ScreenUtil.screenHeight : 设备高度
*/
